﻿using Meiam.System.Interfaces;
using Meiam.System.Interfaces.IService;
using Meiam.System.Model.Entity;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Meiam.System.Model.Dto;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using SqlSugar;
using System.Text;
using System.Data;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Meiam.System.Model;
using Microsoft.Extensions.Logging;
using OfficeOpenXml.FormulaParsing.Excel.Functions.Information;
using System.Web;
using System.Configuration;

namespace Meiam.System.Hostd.Controllers.Gokin
{
    /// <summary>
    /// 跟单猿TMS_同步CRM
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class WaybillInfoSendCRMController : ControllerBase
    {
        private readonly ILogger<WaybillInfoSendWMSRequestDto> _logger;
        public readonly IWMSTokenCheckService _WMSTokenCheckService;
        public readonly string con;



        public WaybillInfoSendCRMController(ILogger<WaybillInfoSendWMSRequestDto> logger,IWMSTokenCheckService wmsTokenCheckService, IConfiguration _configuration)
        {
            _logger = logger;
            _WMSTokenCheckService = wmsTokenCheckService;
             con= _configuration.GetConnectionString("DDM_DbConnection_ZH");
        }

        /// <summary>
        /// 跟单猿TMS_同步CRM
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public IActionResult PostWaybillInfoSendCRM([FromBody] WaybillInfoSendWMSRequestDto strparm)
        {
            string  strMsg = "";
            object log = "";
            log = strparm;
            StringBuilder strSql = new StringBuilder();
            List<string> strSqlList = new List<string>();
            WaybillInfoSendWMSResponseDto re = new WaybillInfoSendWMSResponseDto();
            WaybillInfoSendWMSRequestDto pus = new WaybillInfoSendWMSRequestDto();
            CRM_AddLogisticsInfoRequestDto strRequest = new CRM_AddLogisticsInfoRequestDto();
            CRM_AddLogisticsInfo_header header_input = new CRM_AddLogisticsInfo_header();//operationinfo赋值
            string currentDateTime = DateTime.Now.ToString("yyyyMMddHHmmss");
            string systemid = "ecology9";
            string password = "A5CB8E3D73834CC598DDC659C6F22523";
            string Md5str = MethodHelp.GetMD5(systemid + password + currentDateTime);
            header_input.systemid = systemid;
            header_input.currentDateTime = currentDateTime;
            header_input.Md5 = Md5str;
            strRequest.header = header_input;//header节点赋值

            try
            {

                Dictionary<string, string> urldic = new Dictionary<string, string>(); //URL获取dic
                urldic.Add("function_description", "内部:新增物流信息");//查看URL配置表地址描述
                DataTable url_dt = MethodHelp.GetTableInfo("TMS0004", urldic, con);//获取URL地址
                if (url_dt.Rows.Count > 0)
                {
                    Dictionary<string, string> dic = new Dictionary<string, string>(); //查询公用dic
                    dic = new Dictionary<string, string>(); //查询公用dic
                    dic.Add("organization", "");//查询参数
                    DataTable push_dt = MethodHelp.GetTableInfo("TMS0040", dic, con);//获取推送数据
                    if (push_dt.Rows.Count > 0)
                    {
                        foreach (DataRow item in push_dt.Rows)
                        {
                            if (item["saleNo"].ToString()!="")
                            {
                                int sfyqs = 1;
                                int yszt = 1;
                                string logisticsDetailsId= item["logisticsDetailsId"].ToString();
                                if (item["metadataName"].ToString() == "已签收")
                                {
                                    sfyqs = 0;
                                    yszt = 3;

                                    string[] parts = logisticsDetailsId.Split("-");

                                    dic = new Dictionary<string, string>(); //查询公用dic
                                    dic.Add("transportOrderNo", item["transportOrderNo"].ToString());//查询参数
                                    dic.Add("logisticsDetailsId", parts[2].ToString());
                                    DataTable id_dt = MethodHelp.GetTableInfo("TMS0049", dic, con);//获取已提货ID
                                    if (id_dt.Rows.Count>0)
                                    {

                                        logisticsDetailsId = id_dt.Rows[0]["logisticsDetailsId"].ToString();
                                    }

                                }
                                else
                                {
                                    sfyqs = 1;
                                    yszt = 1;
                                }
                                List<CRM_AddLogisticsInfo_data> data_input = new List<CRM_AddLogisticsInfo_data>();//operationinfo赋值
                                CRM_AddLogisticsInfo_operationinfo operationinfo_input = new CRM_AddLogisticsInfo_operationinfo();//operationinfo赋值
                                CRM_AddLogisticsInfo_mainTable mainTable_input = new CRM_AddLogisticsInfo_mainTable();//mainTable赋值
                                List<CRM_AddLogisticsInfo_qsdfj> qsdfj_input = new List<CRM_AddLogisticsInfo_qsdfj>();

                                //operationinfo_input赋值
                                operationinfo_input.operationDate = DateTime.Now.ToString("yyyy-MM-dd");
                                operationinfo_input.operationTime = DateTime.Now.ToString("HH:mm:ss");
                                operationinfo_input.creator = "1";

                                if (item["filePath"].ToString() != "")
                                {
                                    //mainTable_input赋值
                                    qsdfj_input.Add(new CRM_AddLogisticsInfo_qsdfj
                                    {
                                        name = item["fileName1"].ToString(),
                                        content = item["filePath"].ToString()
                                    });
                                }
                                if (item["filePath2"].ToString() != "")
                                {
                                    //mainTable_input赋值
                                    qsdfj_input.Add(new CRM_AddLogisticsInfo_qsdfj
                                    {
                                        name = item["fileName2"].ToString(),
                                        content = item["filePath2"].ToString()
                                    });
                                }

                                if (item["filePath"].ToString().Trim() == "" & item["filePath2"].ToString().Trim() == "")
                                {   //mainTable_input赋值
                                    qsdfj_input.Add(new CRM_AddLogisticsInfo_qsdfj
                                    {
                                        name = "无",
                                        content = ""
                                    });

                                }
                                mainTable_input.qsdfj = qsdfj_input;
                                mainTable_input.xsddh = item["saleNo"].ToString();
                                mainTable_input.ddxh = item["subSaleNo"].ToString();
                                mainTable_input.qssl = DB.ToDecimal(item["goodsTotal"].ToString());
                                mainTable_input.wlfy = 0;
                                mainTable_input.yszt = yszt;
                                mainTable_input.sfyqs = sfyqs;
                                mainTable_input.qsrq = DB.ToDateTime(item["operatorTime"].ToString()).ToString("yyyy-MM-dd");
                                mainTable_input.khbm = item["transportOrderNo"].ToString();
                                mainTable_input.cph = item["planeNumber"].ToString();
                                mainTable_input.wlbm = item["goodsCode"].ToString();
                                mainTable_input.wlmc = item["goodsName"].ToString();
                                mainTable_input.wldw = "";
                                mainTable_input.ddsl = DB.ToDecimal(item["goodsTotal"].ToString());
                                mainTable_input.pdatjsl = DB.ToDecimal(item["goodsTotal"].ToString());
                                mainTable_input.fhdz = "";
                                mainTable_input.shdz = item["loadAddress"].ToString();
                                mainTable_input.shr = item["deliverUserName"].ToString();
                                mainTable_input.shdh = item["deliverUserPhone"].ToString();
                                mainTable_input.xshth = "";
                                mainTable_input.qsdh = "";
                                mainTable_input.qszt = "";
                                mainTable_input.sj = item["driverMaName"].ToString();
                                mainTable_input.khmc = item["deliverCompanyName"].ToString();
                                mainTable_input.chrq = DB.ToDateTime(item["operatorTime"].ToString()).ToString("yyyy-MM-dd"); ;
                                mainTable_input.hth = "";
                                mainTable_input.ddlx = "";
                                mainTable_input.fhsl = DB.ToDecimal(item["goodsTotal"].ToString());
                                mainTable_input.ydzt = 0;
                                mainTable_input.khbh = item["deliverCompanyCode"].ToString();
                                mainTable_input.xsddid = "";
                                mainTable_input.xsddxid = item["subSaleNo"].ToString();
                                mainTable_input.ckdh = "";
                                mainTable_input.songhdh = "";
                                mainTable_input.yjft = 0;
                                mainTable_input.fyjhls = "";
                                mainTable_input.zt = 2;
                                mainTable_input.ydzbid = item["transportOrderNo"].ToString();
                                mainTable_input.xsddmxid = logisticsDetailsId;
                                mainTable_input.szjd = "";


                                if (mainTable_input != null && operationinfo_input != null)
                                {
                                    data_input.Add(new CRM_AddLogisticsInfo_data
                                    {
                                        operationinfo = operationinfo_input,
                                        mainTable = mainTable_input
                                    });
                                }

                                if (data_input != null)
                                {
                                    strRequest.data = data_input;
                                }

                                string jsonText = JsonConvert.SerializeObject(strRequest);
                                var reAgv = DB.httpPost(url_dt.Rows[0]["interface_url"].ToString(), jsonText, "", "否");
                                CRM_AddLogisticsInfoResponseDto psp = JsonConvert.DeserializeObject<CRM_AddLogisticsInfoResponseDto>(reAgv);
                                if (psp.status != "1")
                                {
                                    strMsg = strMsg + "-" + "CRM ERR:" + psp.datajson;
                                }
                                else
                                {
                                    dic = new Dictionary<string, string>();
                                    dic.Add("logisticsDetailsId", item["logisticsDetailsId"].ToString());
                                    strMsg = MethodHelp.InsertIntoTable("TMS0041", dic, con);
                                }
                            }                                                       
                        }

                    }
                }
               
            }
            catch (Exception ex)
            {
                strMsg = ex.ToString();
            }

         


            if (strMsg=="")
            {
                re.code = 0;
               
            }
            else
            {
                re.code = 500;
                re.message = strMsg;
            }


            return new JsonResult(re);
        }

      
    }
}
